const tabTimers = {};

function getTimerInfo(tabId) {
  return tabTimers[tabId] || {
    refreshInterval: null,
    countdownInterval: null,
    nextRefreshTime: null,
    interval: null,
    timeUnit: null,
    lastActiveTime: null  // 添加最后活动时间
  };
}

function updateBadgeText(tabId) {
  chrome.tabs.query({active: true, currentWindow: true}).then(tabs => {
    const currentTabId = tabs[0]?.id;
    const timerInfo = getTimerInfo(currentTabId);
    
    // 检查定时器是否仍然有效
    if (timerInfo.nextRefreshTime) {
      const now = Date.now();
      timerInfo.lastActiveTime = now;  // 更新最后活动时间

      const remainingSeconds = Math.max(0, Math.ceil((timerInfo.nextRefreshTime - now) / 1000));
      chrome.action.setBadgeText({ text: remainingSeconds.toString() });
      chrome.action.setBadgeBackgroundColor({ color: '#4688F1' });
    } else {
      chrome.action.setBadgeText({ text: '' });
    }
  }).catch(error => {
    console.error('Update badge error:', error);
  });
}

function startRefresh(tabId, interval, timeUnit) {
  try {
    const timerInfo = getTimerInfo(tabId);
    
    // 清理现有定时器
    if (timerInfo.refreshInterval) {
      clearInterval(timerInfo.refreshInterval);
    }
    if (timerInfo.countdownInterval) {
      clearInterval(timerInfo.countdownInterval);
    }
    
    timerInfo.interval = interval;
    timerInfo.timeUnit = timeUnit;
    timerInfo.lastActiveTime = Date.now();
    tabTimers[tabId] = timerInfo;

    // 计算刷新间隔（毫秒）
    const refreshInterval = timeUnit === 'second' ? interval * 1000 : interval * 60 * 1000;
    
    timerInfo.nextRefreshTime = Date.now() + refreshInterval;

    // 创建刷新定时器
    timerInfo.refreshInterval = setInterval(() => {
      chrome.tabs.get(tabId).then(tab => {
        if (tab) {
          const now = Date.now();
          // 检查是否长时间未活动（超过两个刷新间隔）
          if (now - timerInfo.lastActiveTime > refreshInterval * 2) {
            console.log('Timer inactive for too long, restarting...');
            // 重新启动定时器
            startRefresh(tabId, interval, timeUnit);
            return;
          }
          
          chrome.tabs.reload(tabId);
          timerInfo.nextRefreshTime = now + refreshInterval;
          timerInfo.lastActiveTime = now;
        } else {
          stopRefresh(tabId);
        }
      }).catch(error => {
        console.error('Refresh error:', error);
        // 尝试恢复定时器
        setTimeout(() => {
          if (timerInfo.refreshInterval) {  // 如果定时器仍然存在
            startRefresh(tabId, interval, timeUnit);
          }
        }, 5000);  // 5秒后尝试恢复
      });
    }, refreshInterval);

    // 创建倒计时定时器，更频繁地更新以保持活性
    timerInfo.countdownInterval = setInterval(() => {
      try {
        updateBadgeText(tabId);
      } catch (error) {
        console.error('Countdown update error:', error);
      }
    }, 1000);

    updateBadgeText(tabId);
    return true;
  } catch (error) {
    console.error('Start refresh error:', error);
    return false;
  }
}

function stopRefresh(tabId) {
  try {
    const timerInfo = getTimerInfo(tabId);
    
    if (timerInfo.refreshInterval) {
      clearInterval(timerInfo.refreshInterval);
    }
    if (timerInfo.countdownInterval) {
      clearInterval(timerInfo.countdownInterval);
    }
    
    timerInfo.refreshInterval = null;
    timerInfo.countdownInterval = null;
    timerInfo.nextRefreshTime = null;
    timerInfo.interval = null;
    timerInfo.timeUnit = null;
    timerInfo.lastActiveTime = null;
    
    updateBadgeText(tabId);
    return true;
  } catch (error) {
    console.error('Stop refresh error:', error);
    return false;
  }
}

// 监听标签页切换
chrome.tabs.onActivated.addListener((activeInfo) => {
  try {
    const timerInfo = getTimerInfo(activeInfo.tabId);
    if (timerInfo.refreshInterval) {
      timerInfo.lastActiveTime = Date.now();  // 更新活动时间
    }
    updateBadgeText(activeInfo.tabId);
  } catch (error) {
    console.error('Tab activation error:', error);
  }
});

// 监听标签页更新
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  try {
    const timerInfo = getTimerInfo(tabId);
    if (timerInfo.refreshInterval) {
      timerInfo.lastActiveTime = Date.now();  // 更新活动时间
    }
  } catch (error) {
    console.error('Tab update error:', error);
  }
});

// 监听标签页关闭
chrome.tabs.onRemoved.addListener((tabId) => {
  try {
    stopRefresh(tabId);
    delete tabTimers[tabId];
  } catch (error) {
    console.error('Tab removal error:', error);
  }
});

// 消息监听器
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  try {
    if (request.action === 'start') {
      const success = startRefresh(request.tabId, request.interval, request.timeUnit);
      sendResponse({ success });
    } 
    else if (request.action === 'stop') {
      const success = stopRefresh(request.tabId);
      sendResponse({ success });
    } 
    else if (request.action === 'getStatus') {
      const timerInfo = getTimerInfo(request.tabId);
      sendResponse({
        isRunning: !!timerInfo.refreshInterval,
        interval: timerInfo.interval,
        timeUnit: timerInfo.timeUnit,
        nextRefreshTime: timerInfo.nextRefreshTime
      });
    }
    return true;
  } catch (error) {
    console.error('Message handling error:', error);
    sendResponse({ success: false, error: error.message });
    return true;
  }
});